package com.mornd.gulimall.product.service.impl;

import com.mornd.gulimall.product.entity.Brand;
import com.mornd.gulimall.product.mapper.BrandMapper;
import com.mornd.gulimall.product.service.ICacheService;
import org.springframework.cache.annotation.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author: mornd
 * @dateTime: 2023/8/13 - 1:55
 */
@Service
@CacheConfig(cacheNames = "product:brand")
public class CacheServiceImpl implements ICacheService {
    @Resource
    public BrandMapper brandMapper;

    /**
     * 如果缓存有数据，不用调用该方法，如果没有，则执行该方法，最后将结果加入缓存
     *
     *         默认行为：
     *         key：product:brand::SimpleKey []
     *         value默认使用 jdk 的序列化机制
     *         ttl=-1
     *
     *  须在配置文件指定数据有效时间
     *  指定'cache'前缀 => cache:product:brand::brandList
     * @return
     */

    @Cacheable(/*cacheNames = {"product:brand"},*/ key = "#root.method.name") // sync = true 同步执行，加synchronized锁
    @Override
    public List<Brand> brandList() {
        System.out.println("brandList 被调用了");
        List<Brand> brands = brandMapper.selectList(null);
        return brands;
    }

    @Caching(evict = {
            @CacheEvict(/*cacheNames = {"product:brand"}, */ key = "'brandList'")
    }) // 组合多个操作
    //@CacheEvict(cacheNames = {"product:brand"}, key = "'brandList'")
    //@CacheEvict(cacheNames = {"product:brand"}, allEntries = true) // allEntries = true 表示删除product:brand这个分区下的所有数据，通配 product:brand::**
    public void delete() {
        System.out.println("delete 方法被调用");
    }
}
